const request = require('../../../api/request');

// 性别映射函数
function genderText(gender) {
  if (gender === 'M') return '男';
  if (gender === 'F') return '女';
  return '未知';
}

Page({
  data: {
    form: {
      username: '',
      nickname: '',
      clanId: '',
      branchId: '',
      avatar: ''
    },
    clanList: [],
    branchList: [],
    clanIndex: 0,
    branchIndex: 0,
    // 新增成员搜索相关
    searchKeyword: '',
    memberList: [],
    memberIndex: 0,
    selectedMember: null,
    memberId: null,
    memberListTruncated: false
  },

  onLoad() {
    this.loadClans();
    // 预填昵称、头像
    const userInfo = wx.getStorageSync('userInfo') || {};
    this.setData({
      'form.nickname': userInfo.nickname || '',
      'form.avatar': userInfo.avatar || ''
    });
  },

  // 加载家族列表
  loadClans() {
    request.get('/clans', { page: 1, size: 100 }).then(res => {
      const clanList = res.records || res.data?.records || [];
      let clanId = '';
      let clanIndex = 0;
      if (clanList.length > 0) {
        clanId = clanList[0].id;
        clanIndex = 0;
      }
      this.setData({
        clanList,
        'form.clanId': clanId,
        clanIndex
      });
      if (clanId) {
        this.loadBranches(clanId);
      }
    });
  },

  // 家族选择
  onClanChange(e) {
    const clanIndex = e.detail.value;
    const clanId = this.data.clanList[clanIndex].id;
    this.setData({
      clanIndex,
      'form.clanId': clanId,
      branchList: [],
      branchIndex: 0,
      'form.branchId': '',
      // 清空成员搜索结果
      searchKeyword: '',
      memberList: [],
      memberIndex: 0,
      selectedMember: null,
      memberId: null,
      memberListTruncated: false
    });
    this.loadBranches(clanId);
  },

  // 加载分支列表
  loadBranches(clanId) {
    request.get('/branches', { clanId, page: 1, size: 100 }).then(res => {
      const branchList = res.records || res.data?.records || [];
      let branchId = '';
      let branchIndex = 0;
      if (branchList.length > 0) {
        branchId = branchList[0].id;
        branchIndex = 0;
      }
      this.setData({
        branchList,
        'form.branchId': branchId,
        branchIndex
      });
    });
  },

  // 分支选择
  onBranchChange(e) {
    const branchIndex = e.detail.value;
    const branchId = this.data.branchList[branchIndex].id;
    this.setData({
      branchIndex,
      'form.branchId': branchId,
      // 清空成员搜索结果
      searchKeyword: '',
      memberList: [],
      memberIndex: 0,
      selectedMember: null,
      memberId: null,
      memberListTruncated: false
    });
  },

  // 选择头像
  chooseAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        this.setData({ 'form.avatar': res.tempFilePaths[0] });
      }
    });
  },

  // 输入成员姓名
  onInputMemberKeyword(e) {
    this.setData({ searchKeyword: e.detail.value });
  },
  // 点击按钮主动搜索成员
  onSearchMember() {
    const keyword = this.data.searchKeyword.trim();
    if (keyword.length < 2) {
      wx.showToast({ title: '请输入至少2个字', icon: 'none' });
      this.setData({ memberList: [], selectedMember: null, memberId: null, memberListTruncated: false });
      return;
    }
    request.get('/members', {
      name: keyword,
      clanId: this.data.form.clanId,
      branchId: this.data.form.branchId,
      page: 1,
      size: 20
    }).then(res => {
      const maxShow = 10;
      const memberListRaw = res.records || res.data?.records || [];
      const memberList = memberListRaw.slice(0, maxShow).map(m => ({
        ...m,
        genderLabel: genderText(m.gender),
        displayName: `${m.name}（${genderText(m.gender)}${m.birthYear ? '，' + m.birthYear : ''}${m.branchName ? '，' + m.branchName : ''}${m.fatherName ? '，父：' + m.fatherName : ''}${m.motherName ? '，母：' + m.motherName : ''}）`
      }));
      this.setData({
        memberList,
        memberListTruncated: memberListRaw.length > maxShow
      });
      if (memberListRaw.length === 0) {
        wx.showModal({
          title: '提示',
          content: '成员不存在，请发起一个新增成员任务给到管理员',
          showCancel: false
        });
      }
    });
  },
  // 选择成员（点击按钮）
  onChooseMember(e) {
    const idx = e.currentTarget.dataset.index;
    const member = this.data.memberList[idx];
    this.setData({
      selectedMember: member,
      memberId: member.id
    });
  },

  // 表单提交
  onSubmit(e) {
    const form = e.detail.value;
    // picker索引同步id，防止未手动切换时id为0
    if (this.data.clanList.length > 0) {
      form.clanId = this.data.clanList[this.data.clanIndex].id;
    }
    if (this.data.branchList.length > 0) {
      form.branchId = this.data.branchList[this.data.branchIndex].id;
    }
    // 新增：获取用户id
    const userInfo = wx.getStorageSync('userInfo') || {};
    if (userInfo.id) {
      form.userId = userInfo.id;
    }
    console.log(form)
    console.log(this.data.memberId)
    // 校验
    if (!form.username || !form.clanId || !form.branchId || !this.data.memberId) {
      wx.showToast({ title: '请填写完整信息', icon: 'none' });
      return;
    }
    form.avatar = this.data.form.avatar;
    form.memberId = this.data.memberId;
    // 头像上传（如有变更）
    if (this.data.form.avatar && this.data.form.avatar.startsWith('http')) {
      this.submitProfile(form);
    } else if (this.data.form.avatar) {
      wx.uploadFile({
        url: getApp().globalData.apiBase + '/api/v1/files/upload',
        filePath: this.data.form.avatar,
        name: 'file',
        header: {
          'Authorization': getApp().globalData.token ? 'Bearer ' + getApp().globalData.token : ''
        },
        success: res => {
          const data = JSON.parse(res.data);
          form.avatar = data.url;
          this.submitProfile(form);
        },
        fail: () => {
          wx.showToast({ title: '头像上传失败', icon: 'none' });
        }
      });
    } else {
      this.submitProfile(form);
    }
  },

  // 提交资料
  submitProfile(form) {
    request.post('/users/complete-profile', form).then(() => {
      wx.showToast({ title: '资料已完善', icon: 'success' });
      // 重新获取用户信息
      request.get('/users/me').then(user => {
        wx.setStorageSync('userInfo', user);
        wx.switchTab({ url: '/pages/index/index' });
      });
    }).catch(err => {
      wx.showToast({ title: err.msg || '保存失败', icon: 'none' });
    });
  }
}); 